package com.baidu.ueditor.upload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aliyun.oss.OSSClient;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.dongwu.common.constants.OSSClientConstants;
import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.FileTypeUtils;
import com.dongwu.common.utils.HttpClientUtils;
import com.dongwu.config.AliyunOSSClientUtil;
import com.gexin.fastjson.JSONObject;

public class BinaryUploader {
	
	private static final String image = "image/"; // 图片文件在oss上的文件夹
	
	private static final String audio = "audio/"; // music文件在oss上的文件夹

	private static final String video = "video/"; // video文件在oss上的文件夹
	
	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		State storageState = null;
		String resimageUr = "";
		// FileItemStream fileStream = null;
		// boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) !=
		// null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		// ServletFileUpload upload = new ServletFileUpload(
		// new DiskFileItemFactory());
		//
		// if ( isAjaxUpload ) {
		// upload.setHeaderEncoding( "UTF-8" );
		// }

		try {
			// FileItemIterator iterator = upload.getItemIterator(request);
			//
			// while (iterator.hasNext()) {
			// fileStream = iterator.next();
			//
			// if (!fileStream.isFormField())
			// break;
			// fileStream = null;
			// }
			//
			// if (fileStream == null) {
			// return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			// }
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if (multipartFile == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			// String originFileName = fileStream.getName();
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}
			savePath = PathFormat.parse(savePath, originFileName);
			String basePath = (String) conf.get("basePath");
			// 远程图片上传
			if (basePath.startsWith("http")) {
				String ossPath ="";
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
				if (!FileTypeUtils.isImage(suffix)) {
					// 获取oss目标路径
					ossPath = FileTypeUtils.OSSFileTargetPath(image);
				}
				if (!FileTypeUtils.isVideo(suffix)) {
					// 获取oss目标路径
					ossPath = FileTypeUtils.OSSFileTargetPath(video);
				}
				if (!FileTypeUtils.isAudio(suffix)) {
					// 获取oss目标路径
					ossPath = FileTypeUtils.OSSFileTargetPath(audio);
				}
				File tempFile = FileTypeUtils.MultipartFileToNewFile(multipartFile, filePath);
				// 初始化OSSClient
				OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
				String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, tempFile, OSSClientConstants.BACKET_NAME, ossPath);
//				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
//				File dir = new File(filePath);
//				if (!dir.exists()) {
//					dir.mkdir();
//				}
//				String path = filePath + multipartFile.getOriginalFilename();
//				File tempFile = null;
//				tempFile = new File(path);
//				FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), tempFile);
//				resimageUr = HttpClientUtils.PostFileResMap(getUploadUrlForFileType(basePath,suffix), tempFile);
				storageState = new BaseState();
				storageState.putInfo("size", tempFile.length());
				String imgurl = OSSClientConstants.DOMAIN_HTTP + ossPath + tempFile.getName();
				savePath = imgurl.substring(imgurl.indexOf("/file")+5, imgurl.length());
				
			} else {
				String physicalPath = basePath + savePath;
				// InputStream is = fileStream.openStream();
				InputStream is = multipartFile.getInputStream();
				storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
				is.close();
			}
			if (storageState != null && storageState.isSuccess() || resimageUr != "") {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}
			return storageState;
			// } catch (FileUploadException e) {
			// return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}
	/**
	 * 根绝上传的文件类型选择对应的远程服务器上传接口
	 * 
	 * @param FileUrl
	 * @param suffix
	 * @return
	 */
	private static String getUploadUrlForFileType(String FileUrl,String suffix){
		if(FileTypeUtils.isImage(suffix)){
			return FileUrl+"/image";
		}
		if(FileTypeUtils.isDoc(suffix)){
			return FileUrl+"/doc";
		}
		if(FileTypeUtils.isAudio(suffix)){
			return FileUrl+"/audio";
		}
		if(FileTypeUtils.isVideo(suffix)){
			return FileUrl+"/video";
		}
		return null;
	}
	
	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}

}
